package com.weijf.springboot.interceptors;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class ControllerLogAspect {
	private Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);

	@Pointcut("execution(* com.weijf.springboot.controller..*.*(..))")
	public void controllerLog() {
	}

	@Before("controllerLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        
		logger.info("----IP : " + request.getRemoteAddr());
		logger.info("----ARGS : " + Arrays.toString(joinPoint.getArgs()));
		logger.info("----Target : " + joinPoint.getTarget());

	}

	@AfterReturning(returning = "ret", pointcut = "controllerLog()")
	public void doAfterReturning(Object ret) throws Throwable {
		logger.info("RESPONSE : " + ret);
	}

	@AfterThrowing(throwing = "ex", pointcut = "controllerLog()")
	public void doRecoveryActions(Throwable ex) {
		logger.error("目标方法中抛出的异常:" + ex);
	}
}
